/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.impl.consumer;

import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.common.ServiceThread;
import org.apache.rocketmq.logging.InternalLogger;

/**
 * Rebalance服务。有三种情况会触发Consumer进行Rebalance。
 * 1. RebalanceService是一个线程任务，有MQClientInstance启动，每隔20秒自动进行一次。
 * 2. 由Broker触发:
 * 2.1. Broker收到心跳请求之后如果发现消息中有新的consumer连接或者consumer订阅了新的topic或者移除了topic的订阅，
 * 则Broker发送Code为NOTIFY_CONSUMER_IDS_CHANGED的请求给该group下面的所有Consumer，要求进行一次负载均衡。
 * 处理入口方法为 ClientRemotingProcessor.notifyConsumerIdsChanged().
 * 2.2. 如果某个客户端连接出现连接异常事件EXCEPTION、连接断开事件CLOSE、或者连接闲置事件IDLE，则Broker同样会发送重平衡请求给消费者组下面的所有消费者。
 * 处理入口方法为 ClientHousekeepingService.doChannelCloseEvent().
 * 3. 新的Consumer服务启动的时候，主动调用 MQClientInstance.rebalanceImmediately() 唤醒负载均衡服务rebalanceService.
 * 实际上2.1和2.2最终也是通过调用 MQClientInstance.rebalanceImmediately() 唤醒Rebalance服务。
 *
 * 最终底层都是由 MQClientInstance.doRebalance()完成
 */
public class RebalanceService extends ServiceThread {
    private static long waitInterval =
            Long.parseLong(System.getProperty(
                    "rocketmq.client.rebalance.waitInterval", "20000"));
    private final InternalLogger log = ClientLogger.getLog();
    private final MQClientInstance mqClientFactory;

    public RebalanceService(MQClientInstance mqClientFactory) {
        this.mqClientFactory = mqClientFactory;
    }

    /**
     * 该异步任务的run
     */
    @Override
    public void run() {
        log.info(this.getServiceName() + " service started");
        // 死循环内执行
        while (!this.isStopped()) {
            // 线程等待。默认最多等待20s，期间可以中断等待而被唤醒。
            this.waitForRunning(waitInterval);
            // 执行 Rebalance
            this.mqClientFactory.doRebalance();
        }

        log.info(this.getServiceName() + " service end");
    }

    @Override
    public String getServiceName() {
        return RebalanceService.class.getSimpleName();
    }
}
